import pymongo, error

from configurate import MONGODB


class MongoDbClient(object):
    __instance = None

    """ singleton """
    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super(MongoDbClient, cls).__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        self.conn = None

    def connection(self):
        try:
            if self.conn is None:
                self.conn = pymongo.MongoClient(host=MONGODB.get("host"), port=MONGODB.get("port"))
                print("MongoDB连接成功")
            else:
                print("MongoDB 已连接！！！")
        except Exception as e:
            print(e)
            raise error.MyError(e)

    # 关闭连接 但是感觉没用
    def dispose(self):
        self.conn.close()
